package com.AdvancedDemos.Learn网络编程.CS架构.useTCP1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        //Server接收数据,然后发送回馈

        //服务器socket
        System.out.println("服务端开启");
        // 1、创建ServerSocket的对象，同时为服务端注册端口。
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("等待客户端连接");
        // 2、使用serverSocket对象，调用一个accept方法，产生socket对象,等待客户端的连接请求
        Socket socket = serverSocket.accept();//此方法会阻塞,等待客户端连接
        System.out.println("客户端连接了");

        //接收数据
        //获取字节输入流
        System.out.println("接收数据");
        InputStream inputStream = socket.getInputStream();
        int len;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)/*阻塞,等待发送数据*/) != -1) {
            String s = new String(bytes, 0, len);
            System.out.println(s);
        }
//        inputStream.close();

        //发送数据
        System.out.println("发送数据");
        String data = "我很好!";
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(data.getBytes());
//        outputStream.close();
        System.out.println("发送完成");


        System.out.println("关闭资源");
        socket.close();
        serverSocket.close();
    }
}
